package logic

import (
	"context"
	"errors"
	"math/rand"
	"strconv"
	"time"
	"videos/model/cache"
	"videos/pkg"

	"videos/videorpc/internal/svc"
	"videos/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *videorpc.SendSmsRequest) (*videorpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line

	i, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.Mobile).Int()
	if i >= 1 {
		return nil, errors.New("验证码已过期,请重新获取")
	}

	code := rand.Intn(9000) + 1000

	sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if sms.Code != 2 {
		return nil, errors.New(sms.Msg)
	}

	cache.Rdb.Set(l.ctx, "sendSms"+in.Mobile, code, time.Minute*5)

	result, _ := cache.Rdb.Incr(l.ctx, "SendSms"+in.Mobile).Result()
	if result == 1 {
		cache.Rdb.Expire(l.ctx, "SendSms"+in.Mobile, time.Minute*1)
	}

	return &videorpc.SendSmsResponse{}, nil
}
